﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ZK.CoalYardTransManage.Model;
using ZK.Common;
using static ZK.CoalYardTransManage.Model.SysDefinitionEnum;

namespace ZK.CoalYardTransManage
{
    public class WebApiService
    {
        private static readonly string controlName = "autoControlTransport/";//控制器名称
        private static readonly string truckAdmissionUrl = controlName+"truckAdmission";//车辆入场
        private static readonly string truckExitUrl = controlName+"truckExit";//车辆出场
        private static readonly string getTruckYxInfoUrl = controlName + "getTruckYxInfo";//获取当前车辆信息
        private static readonly string truckLoadingUrl = controlName + "truckLoading";//车辆装车
        private static readonly string truckTareUrl = controlName + "truckTare";//车辆除皮
        private static readonly string truckUnloadingUrl = controlName + "truckUnloading";//车辆卸车
        private static readonly string truckWeighUrl = controlName + "truckWeigh";//车辆称重
        private static readonly string truckWeightBillUrl = controlName + "truckWeightBill";//生成磅单
        public static ApiResponseDto Login(string userName, string password, out string errorStr)
        {
            ApiResponseDto dto = new ApiResponseDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("username", userName);
            data.Add("password", password);
            try
            {
                string url = InterfaceExecute.GetUrl("login/login", data);
                ret = HttpClientUtil.doPostMethodToObj(url, out b);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    JToken reData = (JToken)ja["data"];
                    if (reData != null && reData.Count() > 0)
                    {
                        AppSession.UserInfo.Token = reData["deptList"][0]["token"].ToString();
                        AppSession.UserInfo.Id = int.Parse(reData["id"].ToString());
                        AppSession.UserInfo.UserName = reData["userName"].ToString();
                        AppSession.UserInfo.TelePhone = reData["telephone"].ToString();
                        AppSession.UserInfo.DeptName = reData["deptName"].ToString();
                    }
                    dto.Msg = ja["msg"].ToString();
                    dto.Success = bool.Parse(ja["success"].ToString());
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError("用户名为：" + userName + ",登录接口异常返回数据为[" + ret + "],异常信息为:" + ex.Message);
                errorStr = "error";
            }

            return dto;
        }

        /// <summary>
        /// 通过卡号车牌号查询相关信息
        /// </summary>
        /// <param name="cardNum"></param>
        /// <param name="truckNum"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static TransBasicInfo GetInfoByCardTrunkNum(string cardNum, string truckNum, out string errorStr, int state = 0)
        {
            TransBasicInfo model = new TransBasicInfo();
            string ret = "";
            bool b = false;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("card_no", cardNum);
            data.Add("truck_no", truckNum);
            data.Add("state", state.ToString());
            LogHelper.LogInfo("getAllInfo接口传入参数分别为：" + cardNum + "," + truckNum + "," + state.ToString());
            string url = InterfaceExecute.GetUrl("autoTransport/getAllInfo", data);
            try
            {
                ret = HttpClientUtil.doGetMethodToObj(url, out b);
                LogHelper.LogInfo("请求getAllInfo接口返回:" + ret);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    if (ja["codeStatus"].ToString() == "4010")
                    {
                        Login(MyCustomConfig.userInfo.UserName, MyCustomConfig.userInfo.UserPwd, out errorStr);
                        return GetInfoByCardTrunkNum(cardNum, truckNum, out errorStr);
                    }
                    model.IsSuccess = bool.Parse(ja["success"].ToString());
                    model.MsgData = ja["msg"].ToString();

                    JToken cardInfo = ja["data"];
                    if (cardInfo == null || cardInfo.Count() == 0)
                    {
                        return model;
                    }
                    //model.BName = cardInfo["bname"].ToString();
                    if (cardInfo["carrier_name"] != null)
                        model.CarrierName = cardInfo["carrier_name"].ToString();
                    if (cardInfo["coal_name"] != null)
                        model.CoalName = cardInfo["coal_name"].ToString();
                    if (cardInfo["contract_name"] != null)
                        model.ContractName = cardInfo["contract_name"].ToString();
                    if (cardInfo["contract_type"] != null && !string.IsNullOrEmpty(cardInfo["contract_type"].ToString()))
                        model.ContractType = int.Parse(cardInfo["contract_type"].ToString());
                    if (cardInfo["cname"] != null)
                        model.CustomerName = cardInfo["cname"].ToString();
                    //model.Price = double.Parse(cardInfo["price"].ToString());
                    if (cardInfo["truck_type_name"] != null)
                        model.TruckTypeName = cardInfo["truck_type_name"].ToString();
                    if (cardInfo["truck_no"] != null)
                        model.truckNum = cardInfo["truck_no"].ToString();
                    if (cardInfo["rated_load"] != null && !string.IsNullOrEmpty(cardInfo["rated_load"].ToString()))
                        model.ratedLoad = decimal.Parse(cardInfo["rated_load"].ToString());
                    if (cardInfo["tare"] != null && !string.IsNullOrEmpty(cardInfo["tare"].ToString()))
                        model.tare = decimal.Parse(cardInfo["tare"].ToString());
                    if (cardInfo["weightFloatingMz"] != null && !string.IsNullOrEmpty(cardInfo["weightFloatingMz"].ToString()))
                        model.weightFloatingMz = decimal.Parse(cardInfo["weightFloatingMz"].ToString());
                    if (cardInfo["weightFloatingPz"] != null && !string.IsNullOrEmpty(cardInfo["weightFloatingPz"].ToString()))
                        model.weightFloatingPz = decimal.Parse(cardInfo["weightFloatingPz"].ToString());
                    if (cardInfo["yx_state"] != null && !string.IsNullOrEmpty(cardInfo["yx_state"].ToString()))
                    {
                        model.yx_State = (YxState)int.Parse(cardInfo["yx_state"].ToString());
                    }
                    if (ja["codeStatus"] != null && !string.IsNullOrEmpty(ja["codeStatus"].ToString()))
                    {
                        model.codeStatus = int.Parse(ja["codeStatus"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return model;
        }

        #region 获取当前车辆信息接口
        /// <summary>
        /// 获取当前车辆信息接口
        /// </summary>
        /// <param name="truckNo"></param>
        /// <param name="cardNo"></param>
        /// <returns></returns>
        public static string GetTruckYxInfo(string truckNo, string cardNo="")
        {
            string ret = "";
            bool b = false;
            string errorStr = string.Empty;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("truckNo", truckNo);
            data.Add("cardNo", cardNo);
            LogHelper.LogInfo("getAllInfo接口传入参数分别为：" + truckNo + "," + cardNo + ",");
            string url = InterfaceExecute.GetUrl(getTruckYxInfoUrl, data);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, null, out b);

            }
            catch (Exception ex)
            {
                errorStr = ex.ToString(); 
                LogHelper.LogError(errorStr);
            }
            return ret;
        }

        #endregion

        #region 车辆入场接口
        /// <summary>
        /// 车辆入场接口
        /// </summary>
        /// <param name="cardNo">卡号 </param>
        /// <param name="imgs1">抓拍图片1,多张图片用逗号隔开 ,</param>
        /// <param name="truckNo">车牌号</param>
        /// <returns></returns>
        public static string TruckAdmission(string cardNo,string imgs1,string truckNo)
        {
            string ret = "";
            bool b = false;
            string errorStr = string.Empty;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("truckNo", truckNo);
            data.Add("cardNo", cardNo);
            data.Add("imgs1", imgs1);
            LogHelper.LogInfo("TruckAdmission接口传入参数分别为：" + truckNo + "," + cardNo + ",");
            string url = InterfaceExecute.GetUrl(truckAdmissionUrl);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, HttpClientUtil.GetJsonStr(data), out b);
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return ret;
        }
        #endregion

        #region 车辆出场接口
        /// <summary>
        /// 车辆出场接口
        /// </summary>
        /// <param name="cardNo">卡号 </param>
        /// <param name="imgs1">抓拍图片1,多张图片用逗号隔开 ,</param>
        /// <param name="truckNo">车牌号</param>
        /// <returns></returns>
        public static string TruckExit(string cardNo, string imgs1, string truckNo)
        {
            string ret = "";
            bool b = false;
            string errorStr = string.Empty;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("truckNo", truckNo);
            data.Add("cardNo", cardNo);
            data.Add("imgs1", imgs1);
            LogHelper.LogInfo("TruckExit接口传入参数分别为：" + truckNo + "," + cardNo + ",");
            string url = InterfaceExecute.GetUrl(truckExitUrl);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, HttpClientUtil.GetJsonStr(data), out b);
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return ret;
        }
        #endregion

        #region 车辆装车接口
        /// <summary>
        /// 车辆装车接口
        /// </summary>
        /// <param name="cardNo">卡号 ,</param>
        /// <param name="imgs1">抓拍1,多张图片用逗号隔开 ,</param>
        /// <param name="truckNo">车牌号</param>
        /// <param name="bunkerId">仓场id ,</param>
        /// <param name="memo">备注 </param>
        /// <returns></returns>
        public static string TruckLoading(string cardNo, string imgs1, string truckNo,int bunkerId,string memo)
        {
            string ret = "";
            bool b = false;
            string errorStr = string.Empty;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("truckNo", truckNo);
            data.Add("cardNo", cardNo);
            data.Add("imgs1", imgs1);
            data.Add("bunkerId", bunkerId.ToString());
            data.Add("memo", memo);
            LogHelper.LogInfo("TruckLoading接口传入参数分别为：" + truckNo + "," + cardNo + ",");
            string url = InterfaceExecute.GetUrl(truckLoadingUrl);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, HttpClientUtil.GetJsonStr(data), out b);
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return ret;
        }
        #endregion

        #region 车辆除皮接口
        /// <summary>
        /// 车辆除皮接口
        /// </summary>
        /// <param name="cardNo">卡号 </param>
        /// <param name="imgs1">抓拍图片1,多张图片用逗号隔开 ,</param>
        /// <param name="truckNo">车牌号</param>
        /// <param name="pz">皮重 ,</param>
        /// <param name="wgbid">地磅id</param>
        /// <returns></returns>
        public static string TruckTare(string cardNo, string imgs1, string truckNo,decimal pz,int wgbid)
        {
            string ret = "";
            bool b = false;
            string errorStr = string.Empty;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("truckNo", truckNo);
            data.Add("cardNo", cardNo);
            data.Add("imgs1", imgs1);
            data.Add("pz", pz.ToString());
            data.Add("wgbid", wgbid.ToString());
            LogHelper.LogInfo("CarOut接口传入参数分别为：" + truckNo + "," + cardNo + ",");
            string url = InterfaceExecute.GetUrl(truckTareUrl);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, HttpClientUtil.GetJsonStr(data), out b);
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return ret;
        }
        #endregion

        #region 车辆卸车接口
        /// <summary>
        /// 车辆卸车接口
        /// </summary>
        /// <param name="cardNo">卡号 </param>
        /// <param name="imgs1">抓拍图片1,多张图片用逗号隔开 ,</param>
        /// <param name="truckNo">车牌号</param>
        /// <param name="buckleWeight">扣重</param>
        /// <param name="buckleWeightReason">扣重原因</param>
        /// <param name="bunkerId">仓场id ,</param>
        /// <param name="memo">备注 </param>
        /// <returns></returns>
        public static string TruckUnloading(string cardNo, string imgs1, string truckNo,
            decimal buckleWeight,string buckleWeightReason,int bunkerId,string memo)
        {
            string ret = "";
            bool b = false;
            string errorStr = string.Empty;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("truckNo", truckNo);
            data.Add("cardNo", cardNo);
            data.Add("imgs1", imgs1);
            data.Add("buckleWeight", buckleWeight.ToString());
            data.Add("buckleWeightReason", buckleWeightReason.ToString());
            data.Add("bunkerId", bunkerId.ToString());
            data.Add("memo", memo);
            LogHelper.LogInfo("TruckUnloading接口传入参数分别为：" + truckNo + "," + cardNo + ",");
            string url = InterfaceExecute.GetUrl(truckUnloadingUrl);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, HttpClientUtil.GetJsonStr(data), out b);
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return ret;
        }
        #endregion

        #region 车辆称重接口
        /// <summary>
        /// 车辆称重接口
        /// </summary>
        /// <param name="cardNo">卡号 </param>
        /// <param name="imgs1">抓拍图片1,多张图片用逗号隔开 ,</param>
        /// <param name="truckNo">车牌号</param>
        /// <param name="mz">毛重</param>
        /// <param name="wgbid">地磅id</param>
        /// <returns></returns>
        public static string TruckWeigh(string cardNo, string imgs1, string truckNo,decimal mz,int wgbid)
        {
            string ret = "";
            bool b = false;
            string errorStr = string.Empty;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("truckNo", truckNo);
            data.Add("cardNo", cardNo);
            data.Add("imgs1", imgs1);
            data.Add("mz", mz.ToString());
            data.Add("wgbid", wgbid.ToString());
            LogHelper.LogInfo("TruckWeigh接口传入参数分别为：" + truckNo + "," + cardNo + ",");
            string url = InterfaceExecute.GetUrl(truckWeighUrl);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, HttpClientUtil.GetJsonStr(data), out b);
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return ret;
        }
        #endregion

        #region 生成磅单接口
        /// <summary>
        /// 生成磅单接口
        /// </summary>
        /// <param name="cardNo">卡号 </param>
        /// <param name="truckNo">车牌号</param>
        /// <returns></returns>
        public static string TruckWeightBill(string cardNo,  string truckNo)
        {
            string ret = "";
            bool b = false;
            string errorStr = string.Empty;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("truckNo", truckNo);
            data.Add("cardNo", cardNo);
            LogHelper.LogInfo("TruckWeightBill接口传入参数分别为：" + truckNo + "," + cardNo + ",");
            string url = InterfaceExecute.GetUrl(truckWeightBillUrl);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, HttpClientUtil.GetJsonStr(data), out b);
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return ret;
        }
        #endregion

        /// <summary>
        /// 车辆入场
        /// </summary>
        /// <param name="cardNum"></param>
        /// <param name="truckNum"></param>
        /// <param name="ErrorStr"></param>
        /// <returns></returns>
        public static ApiResponseDto CheckTruckEntrance(string cardNum, string truckNum, string img, out string errorStr)
        {
            ApiResponseDto dto = new ApiResponseDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            jsonStr.Add("card_no", cardNum);
            jsonStr.Add("truck_no", truckNum);
            jsonStr.Add("img1", img);
            LogHelper.LogInfo("入场接口传入参数分别为：" + cardNum + "," + truckNum + "," + img);
            try
            {
                string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
                string url = InterfaceExecute.GetUrl("autoTransport/truckEntrance", null);
                ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
                LogHelper.LogInfo("请求入场接口返回:" + ret);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    dto.Msg = ja["msg"].ToString();
                    dto.Success = bool.Parse(ja["success"].ToString());
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return dto;
        }

        /// <summary>
        /// 车辆除皮
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static ApiResponseDto CheckTruckTare(TareWeightDto dto, out string errorStr)
        {
            ApiResponseDto resDto = new ApiResponseDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            string strImg = string.Empty;
            jsonStr.Add("card_no", dto.CardNum);
            jsonStr.Add("truck_no", dto.TruckNum);
            jsonStr.Add("pz", dto.TareWeight.ToString());
            jsonStr.Add("bunker_id", MyCustomConfig.bunkerInfo.BunkerId);
            LogHelper.LogInfo("除皮接口传入参数分别为：" + dto.CardNum + "," + dto.TruckNum + "," + dto.TareWeight.ToString() + "," + MyCustomConfig.bunkerInfo.BunkerId);
            if (dto.ImageUrl != null && dto.ImageUrl.Length > 0)
            {
                for (int i = 0; i < dto.ImageUrl.Length; i++)
                {
                    strImg += "," + dto.ImageUrl[i];
                }
                jsonStr.Add("img1", strImg.Substring(1));
            }
            string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
            string url = InterfaceExecute.GetUrl("autoTransport/getTare", null);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
                LogHelper.LogInfo("请求除皮接口返回:" + ret);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    if (ja["codeStatus"].ToString() == "4010")
                    {
                        Login(MyCustomConfig.userInfo.UserName, MyCustomConfig.userInfo.UserPwd, out errorStr);
                        return CheckTruckTare(dto, out errorStr);
                    }
                    resDto.Msg = ja["msg"].ToString();
                    resDto.Success = bool.Parse(ja["success"].ToString());
                }
                if (!string.IsNullOrEmpty(errorStr))
                {
                    LogHelper.LogError("除皮接口返回错误:" + errorStr);
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return resDto;
        }

        /// <summary>
        /// 毛重
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static ApiResponseDto CheckGrossWeight(GrossWeightDto dto, out string errorStr)
        {
            ApiResponseDto resDto = new ApiResponseDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            string strImg = string.Empty;
            jsonStr.Add("card_no", dto.CardNum);
            jsonStr.Add("mz", dto.GrossWeight.ToString());
            jsonStr.Add("truck_no", dto.TruckNum);
            jsonStr.Add("bunker_id", MyCustomConfig.bunkerInfo.BunkerId);
            //jsonStr.Add("weighType", dto.WeighType.ToString());
            LogHelper.LogInfo("称重接口传入参数分别为：" + dto.CardNum + "," + dto.TruckNum + "," + dto.GrossWeight.ToString() + "," + MyCustomConfig.bunkerInfo.BunkerId);
            if (dto.ImageUrl != null && dto.ImageUrl.Length > 0)
            {
                for (int i = 0; i < dto.ImageUrl.Length; i++)
                {
                    strImg += "," + dto.ImageUrl[i];
                }
                jsonStr.Add("img2", strImg.Substring(1));
            }
            string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
            string url = InterfaceExecute.GetUrl("autoTransport/grossWeight", null);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
                LogHelper.LogInfo("请求称重接口返回:" + ret);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    if (ja["codeStatus"].ToString() == "4010")
                    {
                        Login(MyCustomConfig.userInfo.UserName, MyCustomConfig.userInfo.UserPwd, out errorStr);
                        return CheckGrossWeight(dto, out errorStr);
                    }
                    resDto.Msg = ja["msg"].ToString();
                    resDto.Success = bool.Parse(ja["success"].ToString());
                }
                if (!string.IsNullOrEmpty(errorStr))
                {
                    LogHelper.LogError("称重接口返回错误:" + errorStr);
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return resDto;
        }

        /// <summary>
        /// 车辆终止后重量验证
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static ApiResponseDto StopWeighing(GrossWeightDto dto, out string errorStr)
        {
            ApiResponseDto resDto = new ApiResponseDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            string strImg = string.Empty;
            jsonStr.Add("card_no", dto.CardNum);
            jsonStr.Add("truck_no", dto.TruckNum);
            jsonStr.Add("weight", dto.GrossWeight.ToString());

            if (dto.ImageUrl != null && dto.ImageUrl.Length > 0)
            {
                for (int i = 0; i < dto.ImageUrl.Length; i++)
                {
                    strImg += "," + dto.ImageUrl[i];
                }
                jsonStr.Add("img2", strImg.Substring(1));
            }
            string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
            string url = InterfaceExecute.GetUrl("autoTransport/addWeigheLog", null);

            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    if (ja["codeStatus"].ToString() == "4010")
                    {
                        Login(MyCustomConfig.userInfo.UserName, MyCustomConfig.userInfo.UserPwd, out errorStr);
                        return StopWeighing(dto, out errorStr);
                    }
                    resDto.Msg = ja["msg"].ToString();
                    resDto.Success = bool.Parse(ja["success"].ToString());
                }
                if (!string.IsNullOrEmpty(errorStr))
                {
                    LogHelper.LogError("车辆终止称重接口返回错误:" + errorStr);
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return resDto;
        }

        /// <summary>
        /// 车辆出场
        /// </summary>
        /// <param name="cardNum"></param>
        /// <param name="truckNum"></param>
        /// <param name="img"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static ApiResponseDto CheckTruckExit(string cardNum, string truckNum, string img, out string errorStr)
        {
            ApiResponseDto dto = new ApiResponseDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            jsonStr.Add("card_no", cardNum);
            jsonStr.Add("truck_no", truckNum);
            jsonStr.Add("img1", img);
            LogHelper.LogInfo("出场接口传入参数分别为：" + cardNum + "," + truckNum + "," + img);
            try
            {
                string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
                string url = InterfaceExecute.GetUrl("autoTransport/truckExit", null);
                ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
                LogHelper.LogInfo("请求出场接口返回:" + ret);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    dto.Msg = ja["msg"].ToString();
                    dto.Success = bool.Parse(ja["success"].ToString());
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return dto;
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="savePath"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static string HttpUploadFile(string filePath, string savePath, out string errorStr)
        {
            string ret = "";
            errorStr = "";
            bool b = false;
            Encoding encoding = Encoding.UTF8;
            string boundary = DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n----" + boundary + "\r\n");
            byte[] endbytes = Encoding.ASCII.GetBytes("\r\n----" + boundary + "--\r\n");

            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("systemType", "cjgmk"); //传文件存储路径
            data.Add("filePath", "cjgmk/" + MyCustomConfig.bunkerInfo.BCode + "/" + DateTime.Now.ToString("yyyyMMdd"));
            string url = InterfaceExecute.GetMediaUrl("importFile", data);

            try
            {
                //1.HttpWebRequest
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=--" + boundary;
                request.Method = "POST";
                request.KeepAlive = true;
                request.Credentials = CredentialCache.DefaultCredentials;
                request.Timeout = 10000;

                using (Stream stream = request.GetRequestStream())
                {

                    //1.1 key/value
                    //string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                    //if (param != null)
                    //{
                    //    foreach (string key in param.Keys)
                    //    {
                    //        stream.Write(boundarybytes, 0, boundarybytes.Length);
                    //        string formitem = string.Format(formdataTemplate, key, param[key]);
                    //        byte[] formitembytes = encoding.GetBytes(formitem);
                    //        stream.Write(formitembytes, 0, formitembytes.Length);
                    //    }
                    //}

                    //1.2 file
                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    string header = string.Format(headerTemplate, "file", Path.GetFileName(filePath));
                    byte[] headerbytes = encoding.GetBytes(header);
                    stream.Write(headerbytes, 0, headerbytes.Length);
                    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            stream.Write(buffer, 0, bytesRead);
                        }
                    }

                    //1.3 form end
                    stream.Write(endbytes, 0, endbytes.Length);
                }
                //2.WebResponse
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                ret = HttpClientUtil.getResponseString(response);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    return ja["data"].ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError("上传抓拍图片返回数据为[" + ret + "],异常信息为:" + ex.Message);
                errorStr = "error";
            }
            return "";
        }

        public static TransBasicInfo GetTruckInfo(string cardNum, string truckNum, out string errorStr)
        {
            TransBasicInfo model = new TransBasicInfo();
            string ret = "";
            bool b = false;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("cardNo", cardNum);
            data.Add("truckNo", truckNum);
            string url = InterfaceExecute.GetUrl("coalSite/getAutoTruckInfo", data);
            try
            {
                ret = HttpClientUtil.doGetMethodToObj(url, out b);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    if (ja["codeStatus"].ToString() == "4010")
                    {
                        Login(MyCustomConfig.userInfo.UserName, MyCustomConfig.userInfo.UserPwd, out errorStr);
                        return GetTruckInfo(cardNum, truckNum, out errorStr);
                    }

                    model.IsSuccess = bool.Parse(ja["success"].ToString());
                    model.MsgData = ja["msg"].ToString();

                    JToken cardInfo = ja["data"];
                    if (cardInfo == null || cardInfo.Count() == 0)
                    {
                        return model;
                    }
                    if (cardInfo["truckNo"] != null)
                        model.truckNum = cardInfo["truckNo"].ToString();
                    if (cardInfo["carrier_name"] != null)
                        model.CarrierName = cardInfo["carrier_name"].ToString();
                    if (cardInfo["coal_name"] != null)
                        model.CoalName = cardInfo["coal_name"].ToString();
                    if (cardInfo["cname"] != null)
                        model.CustomerName = cardInfo["cname"].ToString();
                    if (cardInfo["truck_type_name"] != null)
                        model.TruckTypeName = cardInfo["truck_type_name"].ToString();
                    if (cardInfo["status"] != null && !string.IsNullOrEmpty(cardInfo["status"].ToString()))
                    {
                        model.truckStatus = int.Parse(cardInfo["status"].ToString());
                    }
                    if (cardInfo["ratedLoad"] != null && !string.IsNullOrEmpty(cardInfo["ratedLoad"].ToString()))
                        model.ratedLoad = decimal.Parse(cardInfo["ratedLoad"].ToString());

                    //model.truckNum = cardInfo["truckNo"].ToString();
                    //LogHelper.LogDebug("车牌号为："+ truckNum+",当前状态为：" + Enum.GetName(typeof(TruckState), model.truckStatus));
                    if (cardInfo["tare"] != null && !string.IsNullOrEmpty(cardInfo["tare"].ToString()))
                        model.tare = decimal.Parse(cardInfo["tare"].ToString());
                    if (cardInfo["weightFloatingMz"] != null && !string.IsNullOrEmpty(cardInfo["weightFloatingMz"].ToString()))
                        model.weightFloatingMz = decimal.Parse(cardInfo["weightFloatingMz"].ToString());
                    if (cardInfo["weightFloatingPz"] != null && !string.IsNullOrEmpty(cardInfo["weightFloatingPz"].ToString()))
                        model.weightFloatingPz = decimal.Parse(cardInfo["weightFloatingPz"].ToString());
                    if (ja["codeStatus"] != null && !string.IsNullOrEmpty(ja["codeStatus"].ToString()))
                    {
                        model.codeStatus = int.Parse(ja["codeStatus"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return model;
        }

        /// <summary>
        /// 获取当前状态
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static int GetTransProcess(string cardNum, string truckNum, out string errorStr)
        {
            int truckState = 0;
            string ret = "";
            bool b = false;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("cardNo", cardNum);
            data.Add("truckNo", truckNum);
            string url = InterfaceExecute.GetUrl("coalSite/autoDistinguishProcess", data);
            ret = HttpClientUtil.doGetMethodToObj(url, out b);
            JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
            if (errorStr == "" && ja != null)
            {
                if (ja["codeStatus"].ToString() == "4010")
                {
                    Login(MyCustomConfig.userInfo.UserName, MyCustomConfig.userInfo.UserPwd, out errorStr);
                    return GetTransProcess(cardNum, truckNum, out errorStr);
                }

                if (bool.Parse(ja["success"].ToString()))
                {
                    truckState = int.Parse(ja["success"].ToString());
                }
            }
            return truckState;
        }

        /// <summary>
        /// 调运称重
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static ApiResponseDto TransWeigh(TransWeightDto dto, out string errorStr)
        {
            ApiResponseDto resDto = new ApiResponseDto();
            string ret = "";
            bool b = false;
            string url = "";
            string strImg = string.Empty;
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            jsonStr.Add("cardNo", dto.CardNum);
            jsonStr.Add("truckNo", dto.TruckNum);

            if (dto.ImageUrl != null && dto.ImageUrl.Length > 0)
            {
                for (int i = 0; i < dto.ImageUrl.Length; i++)
                {
                    strImg += "," + dto.ImageUrl[i];
                }
                switch (dto.TruckState)
                {
                    case TruckState.销售装煤_除皮:
                        jsonStr.Add("img1", strImg.Substring(1));
                        break;
                    case TruckState.销售装煤_称重:
                        jsonStr.Add("img2", strImg.Substring(1));
                        break;
                }
            }

            jsonStr.Add("memo", dto.Remark);
            jsonStr.Add("status", ((int)dto.TruckState).ToString());
            //jsonStr.Add("weighType", dto.WeighType.ToString());
            jsonStr.Add("wight", dto.Weight.ToString());
            jsonStr.Add("bunkerId", MyCustomConfig.bunkerInfo.BunkerId);
            string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
            url = InterfaceExecute.GetUrl("coalSite/manualWeighType", null);

            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    if (ja["codeStatus"].ToString() == "4010")
                    {
                        Login(MyCustomConfig.userInfo.UserName, MyCustomConfig.userInfo.UserPwd, out errorStr);
                        return TransWeigh(dto, out errorStr);
                    }
                    resDto.Msg = ja["msg"].ToString();
                    resDto.Success = bool.Parse(ja["success"].ToString());
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return resDto;
        }
        /// <summary>
        /// 创建重量单
        /// </summary>
        /// <param name="cardNum"></param>
        /// <param name="truckNum"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static WeightBillDto CreateWeightBill(string cardNum, string truckNum, out string errorStr)
        {
            WeightBillDto model = new WeightBillDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            jsonStr.Add("card_no", cardNum);
            jsonStr.Add("truck_no", truckNum);
            string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
            string url = InterfaceExecute.GetUrl("autoTransport/getWeightBill", null);
            try
            {
                ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    if (ja["codeStatus"].ToString() == "4010")
                    {
                        Login(MyCustomConfig.userInfo.UserName, MyCustomConfig.userInfo.UserPwd, out errorStr);
                        return CreateWeightBill(cardNum, truckNum, out errorStr);
                    }
                    model.Msg = ja["msg"].ToString();
                    model.Success = bool.Parse(ja["success"].ToString());
                    JToken weightBill = ja["data"];
                    if (weightBill == null || weightBill.Count() == 0)
                    {
                        return model;
                    }
                    model.BillState = int.Parse(weightBill["billstate"].ToString());
                    model.CardNum = weightBill["card_no"].ToString();
                    model.CarrierName = weightBill["carrier_name"].ToString();
                    model.CoalName = weightBill["coal_name"].ToString();
                    model.CustomerName = weightBill["cname"].ToString();
                    model.GrossWeight = double.Parse(weightBill["mz"].ToString());
                    model.Tare = double.Parse(weightBill["pz"].ToString());
                    model.SettleStare = int.Parse(weightBill["settle_stare"].ToString());
                    model.SaleName = weightBill["sname"].ToString();
                    model.TruckNum = weightBill["truck_no"].ToString();
                    model.TruckType = weightBill["truck_type"].ToString();
                    model.Wbcode = weightBill["wbcode"].ToString();
                    model.TransSaleType = int.Parse(weightBill["yx_type"].ToString());
                    model.Producer = weightBill["print_user"].ToString();
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return model;
        }

        public static ApiResponseDto SaveWeightScale(ScaleParamDto dto, out string errorStr)
        {
            ApiResponseDto resDto = new ApiResponseDto();
            string ret = "";
            bool b = false;
            string url = "";
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            jsonStr.Add("address", dto.Address);
            jsonStr.Add("coalMineId", dto.CoalMineId.ToString());
            jsonStr.Add("memo", dto.Describe);
            jsonStr.Add("weighbridgeFlag", dto.WeighBridgeFlag);
            jsonStr.Add("weighbridgeName", dto.WeighbridgeName);
            jsonStr.Add("weighbridgeType", dto.WeighType);
            string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
            url = InterfaceExecute.GetUrl("coalSite/saveWeightScale", null);
            ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
            JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
            if (errorStr == "" && ja != null)
            {
                resDto.Msg = ja["msg"].ToString();
                resDto.Success = bool.Parse(ja["success"].ToString());
            }
            return resDto;
        }

        public static WeightBillList GetWeightBillList(WeightBillRequestDto dto, out string errorStr)
        {
            WeightBillList model = new WeightBillList();
            List<WeightBillDto> ListWeightBill = new List<WeightBillDto>();
            string ret = "";
            bool b = false;
            Dictionary<string, string> jsonStr = new Dictionary<string, string>();
            jsonStr.Add("begin_date", dto.BeginDate);
            jsonStr.Add("end_date", dto.EndDate);
            jsonStr.Add("billstate", dto.BillState.ToString());
            jsonStr.Add("currentPage", "1");
            jsonStr.Add("keywords", dto.Keywords);
            jsonStr.Add("pageSize", "10000");
            jsonStr.Add("truck_no", dto.TruckNo);
            string jsonBody = HttpClientUtil.GetJsonStr(jsonStr);
            string url = InterfaceExecute.GetUrl("autoTransport/getWeightBillList", null);
            ret = HttpClientUtil.doPostMethodToObj(url, jsonBody, out b);
            JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
            if (errorStr == "" && ja != null)
            {
                model.Msg = ja["msg"].ToString();
                model.Success = bool.Parse(ja["success"].ToString());
                model.Total = int.Parse(ja["total"].ToString());
                JArray ss = (JArray)ja["data"];
                foreach (JObject item in ss)
                {
                    WeightBillDto weightBill = new WeightBillDto();
                    weightBill.BillState = int.Parse(item["billstate"].ToString());
                    weightBill.CardNum = item["card_no"].ToString();
                    weightBill.CarrierName = item["carrier_name"].ToString();
                    weightBill.CoalName = item["coal_name"].ToString();
                    weightBill.CustomerName = item["cname"].ToString();
                    weightBill.GrossWeight = double.Parse(item["mz"].ToString());
                    weightBill.Tare = double.Parse(item["pz"].ToString());
                    weightBill.SettleStare = int.Parse(item["settle_stare"].ToString());
                    weightBill.SaleName = item["sname"].ToString();
                    weightBill.TruckNum = item["truck_no"].ToString();
                    weightBill.TruckType = item["truck_type"].ToString();
                    weightBill.Wbcode = item["wbcode"].ToString();
                    weightBill.TransSaleType = int.Parse(item["yx_type"].ToString());
                    weightBill.LbsId = item["wbid"].ToString();
                    weightBill.Producer = item["print_user"].ToString();
                    weightBill.PoundTime = item["print_time"].ToString();
                    ListWeightBill.Add(weightBill);
                }
                model.ListWeightBill = ListWeightBill;
            }
            return model;
        }

        /// <summary>
        /// 煤台获取磅单信息（蒋健提供）
        /// </summary>
        /// <param name="cardNum"></param>
        /// <param name="truckNum"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static WeightBillDto GetAutoTruckInfo(string cardNum, string truckNum, out string errorStr)
        {
            WeightBillDto model = new WeightBillDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("card_no", cardNum);
            data.Add("truck_no", truckNum);
            string url = InterfaceExecute.GetUrl("coalSite/getWeightBill", data);
            ret = HttpClientUtil.doGetMethodToObj(url, out b);
            JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
            if (errorStr == "" && ja != null)
            {
                model.Msg = ja["msg"].ToString();
                model.Success = bool.Parse(ja["success"].ToString());
                JToken weightBill = ja["data"];
                if (weightBill == null || weightBill.Count() == 0)
                {
                    return model;
                }
                model.BillState = int.Parse(weightBill["billstate"].ToString());
                model.CardNum = weightBill["card_no"].ToString();
                model.CarrierName = weightBill["carrier_name"].ToString();
                model.CoalName = weightBill["coal_name"].ToString();
                model.CustomerName = weightBill["cname"].ToString();
                model.GrossWeight = double.Parse(weightBill["mz"].ToString());
                model.Tare = double.Parse(weightBill["pz"].ToString());
                model.SettleStare = int.Parse(weightBill["settle_stare"].ToString());
                model.SaleName = weightBill["sname"].ToString();
                model.TruckNum = weightBill["truck_no"].ToString();
                model.TruckType = weightBill["truck_type"].ToString();
                model.Wbcode = weightBill["wbcode"].ToString();
                model.TransSaleType = int.Parse(weightBill["yx_type"].ToString());
                model.Producer = weightBill["print_user"].ToString();
            }
            return model;
        }

        public static ApiResponseDto UpdateWeightBill(int wbId, out string errorStr)
        {
            ApiResponseDto model = new ApiResponseDto();
            string ret = "";
            bool b = false;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("wbid", wbId.ToString());
            string url = InterfaceExecute.GetUrl("autoTransport/updateWeightBill", data);
            ret = HttpClientUtil.doGetMethodToObj(url, out b);
            JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
            if (errorStr == "" && ja != null)
            {
                model.Success = bool.Parse(ja["success"].ToString());
                model.Msg = ja["msg"].ToString();
            }
            return model;
        }
        /// <summary>
        /// 料仓
        /// </summary>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static BunkerListDto GetBunkerList(out string errorStr)
        {
            BunkerListDto model = new BunkerListDto();
            List<BunkerDto> ListBunker = new List<BunkerDto>();
            List<string> listAddressId = new List<string>();
            string ret = "";
            bool b = false;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("currentPage", "1");
            data.Add("pageSize", "10000");
            data.Add("isvalid", "1");
            string url = InterfaceExecute.GetUrl("bunker/getBunkerList", data);
            ret = HttpClientUtil.doGetMethodToObj(url, out b);
            JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
            if (errorStr == "" && ja != null)
            {
                model.Msg = ja["msg"].ToString();
                model.Success = bool.Parse(ja["success"].ToString());
                model.Total = int.Parse(ja["total"].ToString());
                JArray ss = (JArray)ja["data"];
                foreach (JObject item in ss)
                {
                    BunkerDto bunkerDto = new BunkerDto();
                    bunkerDto.addressId = item["addressId"].ToString();
                    if (listAddressId.Contains(bunkerDto.addressId))
                    {
                        continue;
                    }
                    bunkerDto.bunkerId = item["id"].ToString();
                    bunkerDto.bCode = item["bcode"].ToString();
                    bunkerDto.bName = item["bname"].ToString();
                    bunkerDto.address = item["address"].ToString();
                    bunkerDto.coalId = item["coalId"].ToString();
                    bunkerDto.coalName = item["coalName"].ToString();
                    ListBunker.Add(bunkerDto);
                    listAddressId.Add(bunkerDto.addressId);
                }
                model.bunkerList = ListBunker;
            }
            return model;
        }

        public static ListEnteredTruckDto GetEnteredTruckList(out string errorStr)
        {
            ListEnteredTruckDto model = new ListEnteredTruckDto();
            List<EnteredTruckModel> ListEnteredTruck = new List<EnteredTruckModel>();
            string ret = "";
            bool b = false;
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("currentPage", "1");
            data.Add("pageSize", "1000");
            string url = InterfaceExecute.GetUrl("transportProcess/getTransportTruckInfo", data);
            try
            {
                ret = HttpClientUtil.doGetMethodToObj(url, out b);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {
                    model.Msg = ja["msg"].ToString();
                    model.Success = bool.Parse(ja["success"].ToString());
                    model.Total = int.Parse(ja["total"].ToString());
                    JArray ss = (JArray)ja["data"];
                    foreach (JObject item in ss)
                    {
                        EnteredTruckModel enterDto = new EnteredTruckModel();
                        enterDto.TruckNum = item["truckNo"].ToString();
                        enterDto.CardNum = item["cardNo"].ToString();
                        ListEnteredTruck.Add(enterDto);
                    }
                    model.ListEnteredTruck = ListEnteredTruck;
                }
            }
            catch (Exception ex)
            {
                errorStr = ex.ToString();
                LogHelper.LogError(errorStr);
            }
            return model;
        }
    }
}
